package cn.itcast.demo.web;

import cn.itcast.demo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.awt.*;
import java.time.Duration;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    //同步的操作
    @GetMapping("/sync")
    public User getUserSync() {
        log.info("sync 开始执行");
        User user = getUser();
        log.info("sync 执行完毕");
        return user;
    }

    private User getUser() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return User.of("vv", 20);
    }

    //异步操作,Mono代表返回值是一个元素
    @GetMapping("/mono")
    public Mono<User> getUserMono() {
        log.info("mono 开始执行");
        Mono<User> userMono = Mono.fromSupplier(this::getUser);
        log.info("mono 执行完毕");
        return userMono;
    }

    //异步操作，Flux代表返回值是一串元素,组合成json返回
    @GetMapping("/flux")
    public Flux<User> getUserFlux() {
        log.info("flux 开始执行");
        Flux<User> userByFlux = getUserByFlux();
        log.info("flux 执行完毕");
        return userByFlux;
    }

    //异步操作，Flux    数据像流一样，不断生成并返回
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getUserStream() {
        log.info("stream 开始执行");
        Flux<User> userByFlux = getUserByFlux();
        log.info("stream 执行完毕");
        return userByFlux;
    }

    private Flux<User> getUserByFlux() {
        return Flux.interval(Duration.ofSeconds(1)) //每隔1秒发射一个元素
                .take(5) //取前五个元素
                //行为是将i转换为user对象
                .map(i -> User.of("user-" + i, 10 + i.intValue()));
    }

    //创建Flux的API,generate方法,比较抽象不建议使用
    @GetMapping("/getFlux")
    public Flux<String> getFlux() {
        return Flux.generate(sink -> {
            sink.next("generate方法产生Flux序列");//添加元素
            sink.complete();//结束添加
        });
    }
    //创建Flux的API,create方法，建议使用
    @GetMapping("getFlux2")
    public Flux<String> getFlux2() {
        return Flux.create(sink -> {
            sink.next("create方法产生Flux序列");
            sink.next("create方法产生Flux序列2");
            sink.complete();
        });
    }
}
